package com.gr.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.gr.entity.Attr;
import com.gr.entity.AttrGroup;
import com.gr.entity.AttrGroupDto;
import com.gr.entity.ResultEntity;
import com.gr.service.IAttrGroupService;
import com.gr.service.IAttrService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * <p>
 * 属性分组 前端控制器
 * </p>
 *
 * @author guoran
 * @since 2022-05-11
 */
@RestController
@RequestMapping("/group")
public class AttrGroupController {
    @Autowired
    private IAttrGroupService attrGroupService;
    @Autowired
    private IAttrService attrService;
    @GetMapping("/selectGroupsByCategoryId/{categoryId}")
    public ResultEntity<List<AttrGroup>> selectGroupsByCategoryId(@PathVariable("categoryId")Integer categoryId){
        QueryWrapper wrapper=new QueryWrapper();
        wrapper.eq("category_id",categoryId);
        List<AttrGroup> list = attrGroupService.list(wrapper);
        return ResultEntity.ok(list);
    }

    @PostMapping("/add")
    public ResultEntity add(@RequestBody AttrGroup attrGroup){
        attrGroupService.save(attrGroup);
        return ResultEntity.ok();
    }

    @GetMapping("/selectOne/{groupId}")
    public ResultEntity<AttrGroup> selectOne(@PathVariable("groupId")Integer groupId){
        QueryWrapper wrapper=new QueryWrapper();
        wrapper.eq("attr_group_id",groupId);
        AttrGroup one = attrGroupService.getOne(wrapper);
        return ResultEntity.ok(one);
    }

    @PutMapping("/update")
    public ResultEntity update(@RequestBody AttrGroup attrGroup){
        attrGroupService.updateById(attrGroup);
        return ResultEntity.ok();
    }

    //toDo 给属性分组关联属性 理解为批量把属性表id为attrIds的attr_group_id字段改为groupId
    @PostMapping("/attrToGroup")
    public ResultEntity attrToGroup(@RequestBody AttrGroupDto dto){
        QueryWrapper wrapper=new QueryWrapper();
        wrapper.in("attr_id",dto.getAttrIds());
        List<Attr> list = attrService.list(wrapper);
        for (Attr attr:list){
            attr.setAttrGroupId(dto.getGroupId());
        }
        return ResultEntity.ok();
    }
}

